package com.yk.anima.exption;

import com.google.common.collect.ImmutableMap;

import com.yk.anima.response.CommonCode;
import com.yk.anima.response.ResponseResult;
import com.yk.anima.response.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;



/**
 * @author xiaokai
 * @create 2021-05-11 18:15:06
 * @desc...异常信息处理
 */
@ControllerAdvice
@ResponseBody
public class ExceptionCatch {

    //使用Logger打印错误日志
    private static final Logger logger = LoggerFactory.getLogger(ExceptionCatch.class);


    //定义map，配置异常类型所对应的错误代码
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;
    //定义map的builder对象，去构建ImmutableMap
    protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder =
            ImmutableMap.builder();


    @ExceptionHandler(CustomException.class)
    public ResponseResult customException(CustomException e) {
        logger.error("异常信息 catch exception:{}", e.getMessage());
        ResultCode resultCode = e.getResultCode();
        ResponseResult responseResult = new ResponseResult(resultCode);
        return responseResult;

    }

    @ExceptionHandler(Exception.class)
    public ResponseResult exception(Exception exception) {
        logger.error("异常信息 catch exception:{}", exception.getMessage());
        if (EXCEPTIONS == null) {
            //EXCEPTIONS构建成功
            EXCEPTIONS = builder.build();
        }
        ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
        if(resultCode !=null){
            return new ResponseResult(resultCode);
        }else{
            //返回99999异常
            return new ResponseResult(CommonCode.SERVER_ERROR);
        }


    }

    static {
        //定义异常类型所对应的错误代码
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALID_PARAM);

        //ERROR c.x.f.exception.ExceptionCatch - 异常信息 catch exception:null
    }
}

